package com.zhaojonhy.zhaopangwb.Fragment;

import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.net.RequestListener;
import com.sina.weibo.sdk.openapi.StatusesAPI;
import com.sina.weibo.sdk.openapi.UsersAPI;
import com.sina.weibo.sdk.openapi.models.ErrorInfo;
import com.sina.weibo.sdk.utils.LogUtil;
import com.zhaojonhy.zhaopangwb.bean.User;
import com.zhaojonhy.zhaopangwb.ui.MainActivity;
import com.zhaojonhy.zhaopangwb.utils.AccessTokenKeeper;
import com.zhaojonhy.zhaopangwb.utils.BaseApplication;
import com.zhaojonhy.zhaopangwb.utils.Constants;
import com.zhaojonhy.zhaopangwb.R;
import com.zhaojonhy.zhaopangwb.adapter.StatusAdapter;
import com.zhaojonhy.zhaopangwb.bean.Statuses;
import com.zhaojonhy.zhaopangwb.bean.StatusesFriendsTimeline;
import com.zhaojonhy.zhaopangwb.utils.ImageOptHelper;
import com.zhaojonhy.zhaopangwb.utils.TitleBuilder;
import com.zhaojonhy.zhaopangwb.utils.ToastUtils;
import com.zhaojonhy.zhaopangwb.widget.FragmentBack;

import java.util.ArrayList;
import java.util.List;

import static com.zhaojonhy.zhaopangwb.R.id.lv_home;

/**
 * Created by Administrator on 2016/9/5.
 */
public class HomeFragment extends BaseFragment implements FragmentBack{
    private static final String TAG = HomeFragment.class.getName();

    private Context mContext ;
    //获取标题栏
    private TitleBuilder title ;
    private ImageView left_image ;

    private View view ;
    private TextView titleBarTv ;
    /** 当前 Token 信息 */
    private Oauth2AccessToken mAccessToken;
    /** 用于获取微博信息流等操作的API */
    private StatusesAPI mStatusesAPI;
    private UsersAPI mUsersAPI;
    private User user ;
    private ImageLoader imageLoader ;
    private PullToRefreshListView plvHome ;
    private View footView ;
    private StatusAdapter adapter ;
    private List<Statuses> statuses = new ArrayList<Statuses>();
    private int curPage = 1 ;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Log.d("调用了吗？？","onCreateView") ;
        view = View.inflate(activity,R.layout.frag_home,null) ;
        imageLoader = ImageLoader.getInstance() ;

        initView() ;
        loadData( 1 ) ;
        setTitleImg();
        return view;
    }


    private void initView() {

        title = new TitleBuilder(view).setTitleText("首页") ;
        left_image = (ImageView)view.findViewById(R.id.titleBarIvLeft) ;

        plvHome = (PullToRefreshListView)view.findViewById(lv_home) ;
        adapter = new StatusAdapter(activity,statuses) ;
        Log.d("调用了吗？？","new StatusAdapter") ;
        plvHome.setAdapter(adapter); //新建一个空的adapter，在添加数据再notifyDataSetChanged listView
        Log.d("调用了吗？？","setAdapter") ;
        plvHome.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<ListView>() {
            @Override
            public void onRefresh(PullToRefreshBase<ListView> refreshView) {
                loadData( 1 ) ; //加载了第一页
            }
        });

        //不需要手拉加载，判断当显示左后一个Item是加载下一页
        plvHome.setOnLastItemVisibleListener(new PullToRefreshBase.OnLastItemVisibleListener() {
            @Override
            public void onLastItemVisible() {
                loadData( curPage + 1 ) ;
            }
        });
        footView = View.inflate(activity , R.layout.footview_loading , null) ;
    }

    private void loadData(final int page ){
        Log.d("调用了吗？？","loadData") ;
        // 获取当前已保存过的 Token
        mAccessToken = AccessTokenKeeper.readAccessToken(activity);

        Log.d("调用了吗？？","mAccessToken:"+mAccessToken) ;

        // 对statusAPI实例化
        mStatusesAPI = new StatusesAPI(activity, Constants.APP_KEY, mAccessToken);
        mStatusesAPI.friendsTimeline(0L, 0L, 3, page, false, 0, false, new RequestListener() {
            /**
             * 微博 OpenAPI 回调接口。
             */
            @Override
            public void onComplete(String response) {

                if ( page == 1) {
                    statuses.clear(); //加载第一页时清空集合，确保数据是同一个，及下拉刷新
                }

                curPage = page ; //把加载页赋值给当前页

                Gson gson = new Gson() ;
                StatusesFriendsTimeline friendsTimeline =
                        gson.fromJson(response, StatusesFriendsTimeline.class) ;
                addData(friendsTimeline) ; //添加数据
                }

            @Override
            public void onWeiboException(WeiboException e) {
                LogUtil.e(TAG, e.getMessage());
                ErrorInfo info = ErrorInfo.parse(e.getMessage());
                Toast.makeText(activity, info.toString(), Toast.LENGTH_LONG).show();
            }
        });
    }
    private void addData(StatusesFriendsTimeline friendsTimeline){ //添加数据
        Log.d(TAG,"plv_lisview_count() : "+plvHome.getRefreshableView().getFooterViewsCount()) ;
        Log.d("调用了吗？？","addData") ;
        for (Statuses status : friendsTimeline.getStatuses()){
            //接口 List<E>containsboolean contains(Object o)如果列表包含指定的元素，则返回 true。
            // 更确切地讲，当且仅当列表包含满足 (o==null ? e==null : o.equals(e)) 的元素 e 时才返回 true。
            if( !statuses.contains(status)){ //list.contains(Bean) ,防止数据的重复添加
                statuses.add(status) ; //数据添加到集合中
            }
        }

        //可能要开线程
        adapter.notifyDataSetChanged();//适配器更新
        plvHome.onRefreshComplete();

        if (curPage < friendsTimeline.getTotal_number()) { //判断是否继续加载 ,当前页小于总页数
            addFootView(plvHome, footView) ; //继续加载
        }else {
            removeFootView(plvHome, footView) ; //移除加载
        }
    }

    private void addFootView(PullToRefreshListView plvHome, View footView ) {
        ListView lv = plvHome.getRefreshableView() ;
        Log.d(TAG,"lv.getFooterViewsCount()-->" + lv.getFooterViewsCount()) ;
        if(lv.getFooterViewsCount() == 1) {//查看listView的源码此数据是返回listView的List的集合size
            lv.addFooterView(footView); //添加视图，只进行添加一次,当add前count==1 后 count==2
        }
    }

    private void removeFootView(PullToRefreshListView plvHome, View footView) {
        ListView lv = plvHome.getRefreshableView() ;
        if(lv.getFooterViewsCount() > 1) {
            lv.removeFooterView(footView) ;
        }
    }

    @Override
        public void onBack() {
//        Log.d("调用了吗？？","onBack") ;
//        plvHome.setRefreshing(true);
//        Log.d("调用了吗？？","setRefreshing(true)") ;
    }

//    @Override
//    public void onResume() {
//        plvHome.setRefreshing(true);
//        super.onResume();
//    }

    private void setTitleImg(){
        long uid = Long.valueOf(mAccessToken.getUid()).longValue();
        mUsersAPI = new UsersAPI(activity, Constants.APP_KEY, mAccessToken) ;
        mUsersAPI.show(uid, new RequestListener() {
            @Override
            public void onComplete(String response) {
                user = new Gson().fromJson(response,User.class) ;
                String imgUrl = user.getAvatar_large() ;
                left_image.setVisibility(View.VISIBLE);
                left_image.setPadding(12,12,12,12);
                left_image.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        HomeFragment homeFragment = new HomeFragment() ;
                        homeFragment.setCallBackFuc(new MainActivity());
                        homeFragment.OnReceive();
                    }
                });
                imageLoader.displayImage(imgUrl,left_image, ImageOptHelper.getAvatarOptions());
            }

            @Override
            public void onWeiboException(WeiboException e) {

            }
        }) ;
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        BaseApplication application = (BaseApplication) activity.getApplication() ;
        application.currentUser = user ;
    }

}
